<?php


namespace apps\marriage\core\service;


use apps\marriage\core\model\Follow;
use vm\com\BaseService;

class FollowService extends BaseService
{
    /**
     * @return BaseService|QuoteService
     */
    private function getQuoteService()
    {
        return service('Quote', SERVICE_NAMESPACE);
    }

    /**
     * @return BaseService|QuoteAuthorService
     */
    private function getQuoteAuthorService()
    {
        return service('QuoteAuthor', SERVICE_NAMESPACE);
    }

    /**
     * @return BaseService|QuoteReferenceService
     */
    private function getQuoteReferenceService()
    {
        return service('QuoteReference', SERVICE_NAMESPACE);
    }

    /**
     * @return BaseService|UserService
     */
    private function getUserService()
    {
        return service('User', SERVICE_NAMESPACE);
    }

    /**
     * @return Follow
     */
    protected function getModel()
    {
        return new Follow();
    }

    public function save($iid, $iidType, $userId)
    {
        $params = [
            'iid' => $iid,
            'iid_type' => $iidType,
            'user_id' => $userId
        ];
        if($this->info($params)) {
            $this->delete($params);
            if($iidType == Follow::IID_TYPE_QUOTE_AUTHOR) {
                $this->getQuoteAuthorService()->decrease('followers', ['id' => $iid]);
            } else if($iidType == Follow::IID_TYPE_QUOTE_REFERENCE) {
                $this->getQuoteReferenceService()->decrease('followers', ['id' => $iid]);
            } else if($iidType == Follow::IID_TYPE_QUOTE_CONTRIBUTOR) {
                $this->getUserService()->decrease('followers', ['id' => $iid]);
            }

            $this->getUserService()->decrease('follow_num', ['id' => $userId]);
        } else {
            $params['add_time'] = time();
            $this->create($params);
            if($iidType == Follow::IID_TYPE_QUOTE_AUTHOR) {
                $this->getQuoteAuthorService()->increase('followers', ['id' => $iid]);
            } else if($iidType == Follow::IID_TYPE_QUOTE_REFERENCE) {
                $this->getQuoteReferenceService()->increase('followers', ['id' => $iid]);
            } else if($iidType == Follow::IID_TYPE_QUOTE_CONTRIBUTOR) {
                $this->getUserService()->increase('followers', ['id' => $iid]);
            }

            $this->getUserService()->increase('follow_num', ['id' => $userId]);
        }
    }
}